//
//  ViewController.swift
//  GIF分解单帧图片
//
//  Created by app on 2017/4/13.
//  Copyright © 2017年 app. All rights reserved.
//

import UIKit
import ImageIO
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let gifPath = Bundle.main.path(forResource: "plane", ofType: "gif")! as NSString
        let gifData:Data = try!Data(contentsOf: URL(fileURLWithPath: gifPath as String))
        
        let gifDataSourc:CGImageSource = CGImageSourceCreateWithData(gifData as CFData, nil)!
        let gifImageCount = CGImageSourceGetCount(gifDataSourc)
        for i in 0...gifImageCount - 1 {
            
            let imageref:CGImage? = CGImageSourceCreateImageAtIndex(gifDataSourc, i, nil)
            
            let image:UIImage = UIImage(cgImage: imageref!, scale: UIScreen.main.scale, orientation: .up)
            
            let imageData:Data = UIImagePNGRepresentation(image)!
            var docs = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
            let documentDirectory = docs[0]
            
            let imagePath = documentDirectory + "/\(i)" + ".png"
            
            try? imageData.write(to: URL(fileURLWithPath: imagePath), options: .atomic)
            
            print(imagePath)
        }
        
    }


}

